package com.link.gateway.core.filter.global;

import com.link.gateway.core.comproperty.FilterOrderConstants;
import com.link.gateway.core.comproperty.InterfaceLogConstants;
import com.link.gateway.core.comproperty.OtherConstants;
import com.link.gateway.core.utils.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.ExecutionException;


/**
 * @author guoshan
 * @date 2019年07月18日
 * 判断ip是否在黑白名单中，然后进行处理
 * 处理非法请求
 */
@Component
public class LinkBlackWhiteIpFilter implements GlobalFilter, Ordered {
    private static final Logger logger = LogManager.getLogger(LinkBlackWhiteIpFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //跳过检测
        Object ignoreGlobalFilter = exchange.getAttribute(OtherConstants.ATTRIBUTE_IGNORE_GLOBAL_FILTER);
        if (ignoreGlobalFilter != null && (boolean)ignoreGlobalFilter) {
            return chain.filter(exchange);
        }

        //HuangLJ 2019年07月28日

        long clearVarBegin = System.currentTimeMillis();
        ServerHttpRequest request = exchange.getRequest();


        /**
         * 判断是否请求ip是否被允许访问
         */

        String ipAddress = IpUtil.getIpAddress(request);

        String url = request.getPath().toString();
        try {

            String blackIpList = CacheUtil.getBlackIpList(url);
            String whiteIpList = CacheUtil.getWhiteIpList(url);
            boolean allowVisit = TokenUtils.verifyBlackWhite(ipAddress, whiteIpList, blackIpList);
            if (!allowVisit) {
                return ResponseDataUtils.writeWith(InterfaceLogConstants.IP_OVER, "该ip已被限制访问此路径！", "Y", exchange, null);
            }
        } catch (ExecutionException e) {
            logger.error(e.getMessage());
        }
        FunctionTimeUtil.functionTime("LinkRequestHeaderFilterPre", "LinkRequestHeaderFilter", clearVarBegin, System.currentTimeMillis(),false);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return FilterOrderConstants.VERIFY_BLACK_WHITE_IP;
    }
}
